package com.jims.master.common.utils;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.*;
import java.text.MessageFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

public class StringUtil {
	/** 分号 */
	public static final String SEMICOLON=";";
	/** 冒号*/
	public static final String COLON=":";
	/** 逗号*/
	public static final String COMMA = ",";
	/** '/' */
	public static final String SPLIT = "/";
	/** 下划线 */
	public static final String UNDERLINE = "_";
	/** 日志 */
	@SuppressWarnings("unused")
	private static Logger log = Logger.getLogger("app");

	public static final int FRONT = 0;

	public static final int BACK = 1;
	
	static private char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".toCharArray();

	/**
	 * 用指定的字符填充指定的字符串达到指定的长度，并返回填充之后的字符串 <br>
	 * 
	 * @param p_scr
	 *            待填充的字符串
	 * @param p_fill
	 *            填充的字符
	 * @param p_length
	 *            填充之后的字符串总长度
	 * @return String 填充之后的字符串
	 */
	public static String fill(String p_scr, char p_fill, int p_length) {
		return fill(p_scr, p_fill, p_length, FRONT);
	}

	/**
	 * 用指定的字符填充指定的字符串达到指定的长度，并返回填充之后的字符串<br>
	 * 
	 * @param p_scr
	 *            待填充的字符串
	 * @param p_fill
	 *            填充的字符
	 * @param p_length
	 *            填充之后的字符串总长度
	 * @param direction
	 *            填充方向，SerialPart.FRONT 前面，SerialPart.BACK后面
	 * @return String 填充之后的字符串
	 */
	public static String fill(String p_scr, char p_fill, int p_length,
			int direction) {
		/* 如果待填充字符串的长度等于填充之后字符串的长度，则无需填充直接返回 */
		if (p_scr.length() == p_length) {
			return p_scr;
		}
		/* 初始化字符数组 */
		char[] fill = new char[p_length - p_scr.length()];
		/* 填充字符数组 */
		Arrays.fill(fill, p_fill);
		/* 根据填充方向，将填充字符串与源字符串进行拼接 */
		switch (direction) {
		case FRONT:
			return String.valueOf(fill).concat(p_scr);
		case BACK:
			return p_scr.concat(String.valueOf(fill));
		default:
			return p_scr;
		}
	}

	public static List<Integer> toInteger(List<String> convert) {
		List<Integer> converted = new ArrayList<Integer>();
		for (String id : convert) {
			converted.add(new Integer(id));
		}
		return converted;
	}
	
	/**
	 * 将首字母大写
	 * 
	 * @param s
	 */
	public static String toUpperCaseFirstOne(String s) {
        if (Character.isUpperCase(s.charAt(0))){
        	return s;
        }else{
            return (new StringBuilder())
                    .append(Character.toUpperCase(s.charAt(0)))
                    .append(s.substring(1)).toString();
        }    
    }

	/**
	 * 将String类型的id转换为Interger的id
	 * 
	 * @param strIds
	 */
	public static Collection<Integer> toIntegerIds(Collection<String> strIds) {
		Collection<Integer> setIds = new HashSet<Integer>();
		for (Iterator<String> iterator = strIds.iterator(); iterator.hasNext();) {
			Integer id = Integer.parseInt(iterator.next());
			setIds.add(id);
		}
		return setIds;
	}

	/**
	 * 将String Integer,String [],Integer []类型的id转化为类型为Integer的集合
	 * 
	 * @param objIds
	 * @return
	 */
	public static Collection<Integer> toIntegerIds(Object objIds) {
		Collection<Integer> setIds = new HashSet<Integer>();
		if (objIds instanceof String && !"".equals(objIds)) {
			setIds.add(Integer.valueOf(objIds.toString()));
		} else if (objIds instanceof String[]) {
			String[] ids = (String[]) objIds;
			setIds.addAll(toIntegerIds(Arrays.asList(ids)));
		} else if (objIds instanceof Integer) {
			setIds.add((Integer) objIds);
		} else if (objIds instanceof Integer[]) {
			setIds.addAll(Arrays.asList((Integer[]) objIds));
		}
		return setIds;
	}

	/**
	 * 转化对象类型为java.sql.Timestamp
	 * 
	 * @param p_Obj
	 *            待转化对象
	 * @return 转化后对象
	 */
	public static Timestamp converTimestamp(Object p_Obj) {
		String DATE_Pattern = "\\d{4}[-/]\\d{1,2}[-/]\\d{1,2}(\\s\\d{1,2}:\\d{1,2}(:\\d{1,2})?)?";
		if (p_Obj == null || !Pattern.matches(DATE_Pattern, p_Obj.toString())) {
			throw new RuntimeException("无法转换 " + p_Obj.toString()
					+ " 至TIMESTAMP类型");
		}
		StringBuffer temp = new StringBuffer();
		StringTokenizer st = new StringTokenizer(p_Obj.toString(), "-,/,:, ");
		if (st.countTokens() == 3) // 如2002-12-21
		{
			temp.append(p_Obj.toString());
			temp.append(" 00:00:00.0");
		} else if (st.countTokens() == 5) // 如2003-12-21 22:33
		{
			temp.append(p_Obj.toString());
			temp.append(":00.0");
		} else // 如2003-12-21 22:33:00
		{
			temp.append(p_Obj.toString());
			temp.append(".0");
		}
		return Timestamp.valueOf(temp.toString().replace('/', '-'));
	}

	

	/**
	 * 通过struts 2.0的checkboxlist标签上传到后台的字符串通过该方法转换成系统需要的格式 例如:上传的是1, 2,
	 * 3这样的字符串,需要变成{1,2,3}
	 * 
	 * @param busiType
	 * @return
	 */
	public static String getBusiTypeStr(String busiType) {
		String tmpStr = busiType.replaceAll(" ", "");
		return "{" + tmpStr + "}";
	}

	/**
	 * 合并终端号
	 * 
	 * @param terminalNo
	 * @return
	 * @throws Exception
	 */
	public static String mergeTerminalNo(String terminalNo) {
		if (terminalNo == null)
			return null;
		String[] terminalNos = terminalNo.split(",");
		if (terminalNos.length == 1) {
			return terminalNos[0];
		}
		Arrays.sort(terminalNos);
		String num = "0123456789";
		String tn = null;
		int intPos = 0;
		String headStr = null;
		BigInteger lastNum = new BigInteger("0");
		Boolean flg = true;
		String from = null;
		String to = null;
		StringBuffer sb = new StringBuffer();
		// 以头字符串为key,数字为value放入map
		for (int i = 0; i < terminalNos.length; i++) {
			tn = terminalNos[i];
			char[] ch = tn.toCharArray();
			intPos = 0;
			// 找出数字起始位置
			for (int j = ch.length - 1; j > -1; j--) {
				if (num.indexOf(ch[j]) == -1) {
					intPos = j + 1;
					if (flg) {
						headStr = tn.substring(0, intPos);
						if(intPos<tn.length()){
							lastNum = new BigInteger(tn.substring(intPos, tn.length()));
						}
						from = tn;
						to = tn;
						flg = false;
						sb.append(tn);
					} else {
						if (headStr.equals(tn.substring(0, intPos))) {
							if (lastNum.add(new BigInteger("1")).equals(
									new BigInteger(tn.substring(intPos, tn
											.length())))) {
								to = tn;
								lastNum = new BigInteger(tn.substring(intPos,
										tn.length()));
								if (i + 1 == terminalNos.length) {
									sb.append("-" + to);
								}
							} else {
								if (from.equals(to)) {
									sb.append("," + tn);
								} else {
									sb.append("-" + to + "," + tn);
								}
								from = tn;
								to = tn;
								lastNum = new BigInteger(tn.substring(intPos,
										tn.length()));
							}
						} else {
							if (from.equals(to)) {
								sb.append("," + tn);
							} else {
								sb.append("-" + to + "," + tn);
							}
							from = tn;
							to = tn;
							headStr = tn.substring(0, intPos);
							if(intPos<tn.length()){
								lastNum = new BigInteger(tn.substring(intPos, tn.length()));
							}
						}
					}
					break;
				} else if (j == 0) {
					if (flg) {
						headStr = tn.substring(0, intPos);
						lastNum = new BigInteger(tn.substring(intPos, tn
								.length()));
						from = tn;
						to = tn;
						flg = false;
						sb.append(tn);
					} else {
						if (lastNum.add(new BigInteger("1")).equals(
								new BigInteger(tn
										.substring(intPos, tn.length())))) {
							to = tn;
							lastNum = new BigInteger(tn.substring(intPos, tn
									.length()));
							if (i + 1 == terminalNos.length) {
								sb.append("-" + to);
							}
						} else {
							if (from.equals(to)) {
								sb.append("," + tn);
							} else {
								sb.append("-" + to + "," + tn);
							}
							from = tn;
							to = tn;
							lastNum = new BigInteger(tn.substring(intPos, tn
									.length()));
						}
					}
					break;
				}
			}
		}
		return sb.toString();
		/** 上面以Arrays.sort排序, 下面以Map关键字排序 */
		// String[] terminalNos = terminalNo.split(",");
		// String num = "0123456789";
		// String tn = null;
		// int intPos = 0;
		// Map<String, String> map = new HashMap<String, String>();
		// // 以头字符串为key,数字为value放入map
		// for (int i = 0; i < terminalNos.length; i++) {
		// tn = terminalNos[i];
		// char[] ch = tn.toCharArray();
		// intPos = 0;
		// // 找出数字起始位置
		// for (int j = ch.length - 1; j > -1; j--) {
		// if (num.indexOf(ch[j]) == -1) {
		// intPos = j + 1;
		// String headStr = tn.substring(0, intPos);
		// if (!map.containsKey(headStr)) {
		// map.put(headStr, tn.substring(intPos, tn.length()));
		// } else {
		// map.put(headStr, map.get(headStr) + ","
		// + tn.substring(intPos, tn.length()));
		// }
		// break;
		// }
		// if (j == 0) {
		// String headStr = "";
		// if (!map.containsKey(headStr)) {
		// map.put(headStr, tn);
		// } else {
		// map.put(headStr, map.get(headStr) + "," + tn);
		// }
		// }
		// }
		// }
		// String result = "";
		// Iterator headKeys = map.keySet().iterator();
		// while (headKeys.hasNext()) {
		// String head = (String) headKeys.next();
		// String tnByHead = map.get(head);
		// String[] tnsByHead = tnByHead.split(",");
		// int numLength = tnsByHead[0].length();
		// // 把数字存放到新数组
		// int[] sortInt = new int[tnsByHead.length];
		// for (int i = 0; i < tnsByHead.length; i++) {
		// sortInt[i] = Integer.valueOf(tnsByHead[i]).intValue();
		// }
		// // 对数字数组进行升序排序
		// int tempInt;
		// for (int i = 0; i < sortInt.length; i++) {
		// for (int j = sortInt.length - 1; j > i; j--) {
		// if (sortInt[j] < sortInt[j - 1]) {
		// tempInt = sortInt[j];
		// sortInt[j] = sortInt[j - 1];
		// sortInt[j - 1] = tempInt;
		// }
		// }
		// }
		// // 对数字数组补全长度
		// String intStr;
		// for (int i = 0; i < sortInt.length; i++) {
		// intStr = String.valueOf(sortInt[i]);
		// if (intStr.length() < numLength) {
		// for (int j = numLength - intStr.length(); j > 0; j--) {
		// intStr = "0" + intStr;
		// }
		// }
		// tnsByHead[i] = intStr;
		// }
		// List<String> resultList = new ArrayList<String>();
		// int from = 0, to = 0;
		// Boolean serialFlg = true;
		// // 把结果放入List
		// for (int i = 0; i < sortInt.length; i++) {
		// if (serialFlg) {
		// from = i;
		// to = i;
		// serialFlg = false;
		// }
		// if (i != sortInt.length - 1 && sortInt[i] + 1 == sortInt[i + 1]) {
		// to = i + 1;
		// } else {
		// serialFlg = true;
		// if (from == to) {
		// resultList.add(head + tnsByHead[to]);
		// } else {
		// resultList.add(head + tnsByHead[from] + "-" + head
		// + tnsByHead[to]);
		// }
		// }
		// }
		// // 以逗号分开
		// for (int i = 0; i < resultList.size(); i++) {
		// result = result + resultList.get(i) + ",";
		// }
		// resultList.clear();
		// }
		// return result.substring(0, result.length() - 1);
	}


	/**
	 * 字符串转List
	 * 
	 * @param p_Param
	 *            String 待转字符串
	 * @param p_Delim
	 *            String 字符串分隔符
	 * @return List
	 */
	public static List<String> String2List(String p_Param, String p_Delim) {
		if (p_Param == null || p_Param.trim().equals("")) {
			return null;
		}
		StringTokenizer st;
		if (p_Delim != null) {
			st = new StringTokenizer(p_Param, p_Delim);
		} else {
			st = new StringTokenizer(p_Param);
		}
		List<String> result = new ArrayList<String>();
		while (st.hasMoreTokens()) {
			result.add(st.nextToken());
		}
		return result;
	}

	/**
	 * list转字符串
	 * 
	 * @param p_Param
	 *            List 待转list
	 * @param p_Delim
	 *            String 字符串分隔符
	 * @return String
	 */
	public static String list2String(List<String> p_Param, String p_Delim) {
		if (p_Param == null || p_Param.size() <= 0) {
			return null;
		}
		StringBuffer temp = new StringBuffer();
		for (int i = 0; i < p_Param.size(); i++) {
			temp.append(p_Param.get(i));
			temp.append(p_Delim);
		}
		String rel = temp.toString();
		return rel.substring(0,(rel.length()-p_Delim.length()));
	}

	/**
	 * 唯一数组中的重复值并删除空值, 返回值[0]为更改后的数组, [1]为新数组对应老数组的下标位置
	 * 
	 * @param s
	 * @return Object[]
	 */
	public static Object[] uniqueArrayValue(String[] s) {
		if (s == null) {
			return new Object[2];
		}
		List<String> list = new ArrayList<String>();
		List<String> posList = new ArrayList<String>();
		for (int i = 0; i < s.length; i++) {
			if (!s[i].trim().equals("") && !list.contains(s[i].trim())) {
				list.add(s[i]);
				posList.add(String.valueOf(i));
			}
		}
		Object[] objs = new Object[2];
		objs[0] = list.toArray(new String[list.size()]);
		objs[1] = posList.toArray(new String[posList.size()]);
		return objs;
	}

	/**
	 * 转换Double类型
	 * 
	 * @param dbStr
	 * @return
	 */
	public static Double parseDouble(String dbStr) {
		if (dbStr != null && !dbStr.equals("")) {
			return Double.parseDouble(dbStr);
		} else {
			return null;
		}
	}



	/**
	 * 转义字符
	 * 
	 * @param str
	 * @return
	 */
	public static String convertString(String str, String sourceSplit,
			String targetSplit) {
		String[] strs = str.split("");
		int isSplit = 0;
		String returnStr = "";
		for (String s : strs) {
			if ("\"".equals(s) && isSplit == 0) {
				isSplit = 1;
			} else if ("\"".equals(s) && isSplit == 1) {
				isSplit = 0;
			}
			if (isSplit == 1) {
				if (sourceSplit.equals(s)) {
					s = targetSplit;
				}
				returnStr += s;
				continue;
			}
			returnStr += s;
		}
		return returnStr;
	}

	/**
	 * 反转字符串
	 * 
	 * @param strs
	 * @return
	 */
	public static String[] convertInverseString(String[] strs,
			String sourceSplit, String targetSplit) {
		String[] inverseStrs = new String[strs.length];
		for (int i = 0; i < strs.length; i++) {
			inverseStrs[i] = strs[i].replaceAll(sourceSplit, targetSplit);
		}
		return inverseStrs;
	}


	/**
	 * 将指定的字符填充到目标字符中
	 * 例如：targetStr="aaaa{0}bbbbb{1}",fillStrs=new Object[]{"你","好"}
	 * 返回的字符串则是"aaaa你bbbbb好"
	 * 特注：1:如果你fillStrs中有int或Integer的数字的话，会已科学计数法去填充值，
	 * 建议fillStrs数组中都是字符串String型的;2:如果targetStr中有'字符'则需要转义''字符''
	 */
	public static String fillString(String targetStr,Object ... fillStrs){
		String wholeStr = MessageFormat.format(targetStr,fillStrs);
		return wholeStr;
	}
	/** 得到数据库字符串字段的值 */
	public static String getSQLString(String str){
		if(str==null){
			return null;
		}
		return "'".concat(str).concat("'");
	}
	
	/** 得到数据库字符串字段的值(非空) */
	public static String getNotNullSQLStr(String str){
		if(str==null){
			return "''";
		}
		return "'".concat(str).concat("'");
	}
	
	/**
	 * 得到Integer类型的字符型值(此方法主要使用与sql 格式化注入值的时候)
	 * @param num
	 * @return
	 */
	public static String getSQLIntegerForFormat(Integer num){
		if(num==null)
			return null;
		return num.toString();
	}
	/**
	 * json 组合返回数据时候得到id对应的name
	 * @param piType
	 * @param piTaskStatus
	 * @param taskType
	 * @return
	 */
	public static String getResultStr(String piType,String piTaskStatus,String taskType) {	
		String str="";
		if(piType!=null&& !piType.equals("")){
			Map<String, String> statusMap = new HashMap<String, String>();	
			statusMap.put("1", "新装");
			statusMap.put("2", "增终");
			statusMap.put("3", "增共享");
			statusMap.put("4", "移机");
			statusMap.put("5", "换机");
			statusMap.put("6", "撤机");
			statusMap.put("7", "撤共享");
			statusMap.put("8", "变更商户号终端号");
			statusMap.put("9", "遗失补投");
			statusMap.put("z", "综合单");
			statusMap.put("r", "POS机具租赁");
			str = statusMap.get(piType);
		}else if(piTaskStatus!=null && !piTaskStatus.equals("")){
			Map<String, String> statusMap = new HashMap<String, String>();	
			
			statusMap.put("2", "待处理");
			statusMap.put("3", "作废");
			statusMap.put("4", "电话解决");
			statusMap.put("5", "已派工");
			statusMap.put("8", "服务成功");
			statusMap.put("9", "服务不成功");
			statusMap.put("a", "预审通过");
			statusMap.put("b", "服务成功(除订纸)");
			statusMap.put("c", "预销单");		
			statusMap.put("d", "正式销单");
			statusMap.put("e", "未派工(设备已准备)");
			statusMap.put("f", "已派工(设备未准备)");
			statusMap.put("g", "已派工(设备已准备)");
			statusMap.put("h", "已派工(设备无需准备)");
			statusMap.put("i", "待审核");	
			statusMap.put("j", "已生成通知单");
			statusMap.put("k", "待确认");			
			statusMap.put("l", "服务机具已回收");
			statusMap.put("m", "需后续服务");
			statusMap.put("n", "服务不成功(服务结束)");
			statusMap.put("o", "预约失败");
			statusMap.put("q", "已派工电话解决");
			statusMap.put("r", "待异地审核");
			statusMap.put("s", "异地审核不通过");
			str = statusMap.get(piTaskStatus);
		}else if(taskType!=null && !taskType.equals("")){
			Map<String, String> statusMap = new HashMap<String, String>();
			statusMap.put("1", "报修");
			statusMap.put("2", "订纸");
			statusMap.put("3", "报修+订纸");
			statusMap.put("4", "帐务");
			statusMap.put("5", "咨询");
			statusMap.put("6", "培训");
			statusMap.put("7", "报修+培训");
			statusMap.put("8", "订纸+培训");		
			statusMap.put("9", "报修+订纸+培训");
			statusMap.put("a", "新装");
			statusMap.put("b", "增共享");
			statusMap.put("c", "换机");
			statusMap.put("d", "撤机");
			statusMap.put("e", "移机");
			statusMap.put("f", "网点服务");
			statusMap.put("g", "设备更新");			
			statusMap.put("h", "风控任务");
			statusMap.put("i", "增终");
			statusMap.put("j", "撤共享");
			statusMap.put("k", "变更商户号终端号");
			statusMap.put("l", "原机送回");
			statusMap.put("m", "费用");
			statusMap.put("n", "风控");
			statusMap.put("o", "设备核查");
			statusMap.put("p", "遗失补投");
			statusMap.put("z", "综合单");
			statusMap.put("r", "POS机具租赁");
			str = statusMap.get(taskType);
		}
		
	
		return str;
	}
	
	public static String getRiskLevelStr(String riskLevel) {	
		String str="";
		if(riskLevel!=null&& !riskLevel.equals("")){
			Map<String, String> statusMap = new HashMap<String, String>();	
			statusMap.put("1", "A 优质");
			statusMap.put("2", "B 无风险");
			statusMap.put("3", "C 风险低");
			statusMap.put("4", "D1 疑套现低");
			statusMap.put("5", "D2 疑套现中");
			statusMap.put("6", "D3 疑套现高");
			statusMap.put("7", "D4 伪卡风险");
			statusMap.put("8", "E1 套现风险");
			statusMap.put("9", "E2 其他风险");
					
			str = statusMap.get(riskLevel);
		}
		return str;
	}
	/**费用状态*/
	public static String getFeeStatusStr(String ordStatus) {	
		String str="";
		Map<String, String> statusMap = new HashMap<String, String>();	
		statusMap.put("10", "待收");
		statusMap.put("11", "已联系");
		statusMap.put("20", "未派工");
		statusMap.put("21", "已派工");
		statusMap.put("30", "已收款");
		statusMap.put("31", "异常收款");
		statusMap.put("40", "异常未处理");
		statusMap.put("41", "异常已处理");
		statusMap.put("1", "作废");
		str = statusMap.get(ordStatus);
		return str;
	}
	
	public static String getFeeTypeStr(String feeType) {	
		String str="";
		Map<String, String> statusMap = new HashMap<String, String>();	
		statusMap.put("1", "杉德收费");
		statusMap.put("2", "代银行收费");
		str = statusMap.get(feeType);
		return str;
	}
	
	public static String getPiTypeStr(String piType) {	
		String str="";
		Map<String, String> statusMap = new HashMap<String, String>();		
		statusMap.put("a", "1");
		statusMap.put("i", "2");
		statusMap.put("b", "3");
		statusMap.put("c", "5");
		statusMap.put("d", "6");
		statusMap.put("e", "4");
		statusMap.put("j", "7");
		statusMap.put("k", "8");
		statusMap.put("p", "9");
		//added by SongBang MISMAINTAIN-3728 2011-5-3
		statusMap.put("z", "z");
		str = statusMap.get(piType);
		return str;
	}
	
	public static String geCatIdDifStr(String catIoDif) {	
		String str="";
			Map<String, String> statusMap = new HashMap<String, String>();	
			statusMap.put("0", "无(对应'非银行卡')");
			statusMap.put("1", "内卡");
			statusMap.put("2", "外卡");
			statusMap.put("3", "内外一致(对应'内卡+外卡'或'内卡'或'外卡')");
			statusMap.put("4", "内外不一致(对应'内卡+外卡'或'内卡'或'外卡')");
			str = statusMap.get(catIoDif);
		return str;
	}
	
	
	
	/**转换String成Base64编码**/
	public static String base64Encode(String str){
		if(str!=null&&!"".equals(str)){
			byte[] data=str.getBytes();
			char[] out = new char[((data.length + 2) / 3) * 4];

			for (int i = 0, index = 0; i < data.length; i += 3, index += 4){
				boolean quad = false;
				boolean trip = false;
				int val = (0xFF & (int) data[i]);
				val <<= 8;
				if ((i + 1) < data.length){
					val |= (0xFF & (int) data[i + 1]);
					trip = true;
				}
				val <<= 8;
				if ((i + 2) < data.length){
					val |= (0xFF & (int) data[i + 2]);
					quad = true;
				}
				out[index + 3] = alphabet[(quad ? (val & 0x3F) : 64)];
				val >>= 6;
				out[index + 2] = alphabet[(trip ? (val & 0x3F) : 64)];
				val >>= 6;
				out[index + 1] = alphabet[val & 0x3F];
				val >>= 6;
				out[index + 0] = alphabet[val & 0x3F];
			}
			str=new String(out);
		}
		return str;
	}
	
	/**中文字符进行UrlCoder转码**/
	public static String urlEncode(String str){
		if(str!=null&&!"".equals(str)){
			
			try {
				str=URLEncoder.encode(str,"UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return str;
	}
	
	public static String urlDecode(String str){
		if(str!=null&&!"".equals(str)){
			
			try {
				str=URLDecoder.decode(str,"UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return str;
	}
	
	/**
	 *QGMIS-6447任务，卡应用详细导出，字符过滤方法，过滤符号"|" replace with "" create by wxd 2011-03-19
	 *@return	filterStr
	 */
	public static String cardAppExportStringFilter(String filterStr) throws UnsupportedEncodingException{
		//过滤"|"
		if(StringUtils.isNotEmpty(filterStr)){
			return filterStr.replace("|","");
		}else{
			return filterStr;
		}
	}
	
	/**
	 * 用","分隔的字符串转换成数组
	 * @Title: getArrayBySplitStr
	 * @param str
	 * @return String[]
	 */
	public static String[] getArrayBySplitStr(String str){
		String[] objArray = null;
		if(StringUtils.isNotEmpty(str)){
			if(str.indexOf(",") != -1){
				objArray = str.split(",");
			}else {
				objArray = new String[] {str};
			}
		}
		return objArray;
	}
	/**
	 * Map里的key转换成 字符串      IN  查询条件使用
	 * @Title: getStringByKey
	 * @param key
	 * @param paraMap
	 * @param jointFlg   拼接方式：    true: 数组以","拼接;      false:数组以"','"格式拼接;
	 * @return String
	 */
	public static String getStringByKey(String key, Map<String, Object> paraMap, boolean jointFlg){
		String resultStr = "";
		Object obj = paraMap.get(key);
		if(jointFlg){//","格式拼接
			if(obj instanceof String){
				resultStr = (String) paraMap.get(key);
			}else if(obj instanceof String[]){
				String[] objArr =  (String[]) paraMap.get(key);
				for (int i = 0; i < objArr.length; i++) {
					if(StringUtils.isNotEmpty(resultStr)){
						resultStr = resultStr.concat(","+objArr[i]);
					}else {
						resultStr = objArr[i];
					}
				}
			}
		}else {//'',''格式拼接
			if(obj instanceof String){
				String tmpStr = (String) paraMap.get(key);
				if(StringUtils.isNotEmpty(tmpStr)){
					resultStr = "'".concat(tmpStr).concat("'");
				}
			}else if(obj instanceof String[]){
				String[] objArr =  (String[]) paraMap.get(key);
				for (int i = 0; i < objArr.length; i++) {
					if(StringUtils.isNotEmpty(resultStr)){
						resultStr = resultStr.concat("','").concat(objArr[i]);
					}else {
						resultStr = "'".concat(objArr[i]);
					}
				}
				if(StringUtils.isNotEmpty(resultStr)){
					resultStr = resultStr.concat("'");
				}
			}
		}
		return resultStr;
	}
	
	/**
	 * 追加字符空格
	 * @Title: appendSpacing
	 * @param optType      字符类型      2：数字       其他为String
	 * @param sb           导出字符串
	 * @param k            长度
	 * @return void
	 */
	public static void appendSpacing(Integer optType, StringBuilder sb, int k){
//		String flg = "\0";//默认空格
		String flg = " ";//默认空格
		if (optType != null && optType == 2) {
			flg = "0";
		}
		for (int i = 0; i < k; i++) {
			sb.append(flg);
		}
	}

	/**
	 * 根据类型追加
	 * @Title: appendStr
	 * @param str           字符
	 * @param optType       字符类型      2：数字       其他为String
	 * @param sb            导出字符串
	 * @param l             长度
	 * @return void
	 */
	public static void appendStr(String str, Integer optType, StringBuilder sb, int l){
		if (StringUtils.isNotEmpty(str)) {
			if (str.getBytes().length <= l) {
				if (optType != null && optType == 2) {//N类型
					appendSpacing(optType, sb, l - str.getBytes().length);
					sb.append(str);
				}else {
					sb.append(str);
					appendSpacing(optType, sb, l - str.getBytes().length);
				}
			}else {
				appendSpacing(optType, sb, l);
			}
		}else {
			appendSpacing(optType, sb, l);
		}
		//sb.append("|");
	}
	
	
	public static boolean isInteger(String value) {
		try {Integer.parseInt(value);
		return true;}
		catch (NumberFormatException e)
		{return false;}
		}
	
	/**
	 * 判断是否是Integer类型
	 * @param str
	 * @return
	 */
	public static boolean isNumber(String str){
		if(str!=null&&str.length()<11&&!"".equals(str.trim())){
			Pattern pattern = Pattern.compile("[0-9]*"); 
			Matcher isNum = pattern.matcher(str);
			Long number = 0l;
			if(isNum.matches()){
				number=Long.parseLong(str);
			}else{
				return false;
			}
			if(number>2147483647){
				return false;
			}
		}else{
			return false;
		}
		return true;
	}
	
	/**
	 * 使用java正则表达式去掉多余的.与0
	 * @param s
	 * @return 
	 */
	public static String subZeroAndDot(String s){
		if(s.indexOf(".") > 0){
			s = s.replaceAll("0+?$", "");//去掉多余的0
			s = s.replaceAll("[.]$", "");//如最后一位是.则去掉
		}
		return s;
	}
	
	public static  String formatText(String s,Integer length){
		StringBuffer sb = new StringBuffer(s);
		while(sb.toString().getBytes().length < length){
			sb.append(" ");
		}
		return sb.toString();
	}
	
	public static  String formatTextOpposite(String s,Integer length){
		StringBuffer sb = new StringBuffer("");
		while(sb.toString().getBytes().length+s.getBytes().length < length){
			sb.append("0");
		}
		sb.append(s);
		return sb.toString();
	}
	
	/**
	 * 判断是不是数字类型
	 * @Title: isNumeric
	 * @param str
	 * @return
	 * @return boolean
	 */
	public static boolean isNumeric(String str) {
		//Pattern pattern = Pattern.compile("[0-9]*");  //原始正则表达式
		Pattern pattern = Pattern.compile("-?[0-9]+.?[0-9]+");
		return pattern.matcher(str).matches();
	}
	
	/**
	 * 判断是不是Decimal类型
	 * @Title: isDecimal
	 * @param str
	 * @return boolean
	 */
	public static boolean isDecimal(String str) {
		try {
			new BigDecimal(str);
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}
	
	public static int binarySearch(String[] strArray, String target) {
		//System.out.println(strArray[0]);
		//System.out.println(target);
        int min = 0;
        int max = strArray.length - 1;
        //System.out.println("max---"+max);
        while (max >= min) {
            //int mid = (max + min) / 2;
        	//System.out.println("min---"+min);
            if(null != strArray[min]){
            	if (strArray[min].compareToIgnoreCase(target) == 0){ // 如果相等
                    return min;
            	}else if (strArray[min].compareToIgnoreCase(target) < 0){ // 如果小于target
                    min++;
            	}else{
            		min++;
            	}
            }else{
            	min++;
            }
        }
        return -1;
    }
	
	public static String Array2String(String[] strArray) {
		String rel="";
		int min = 0;
        while ((strArray.length-1) >= min) {
        	rel+=strArray[min]+",";
        	min++;
        }
        return rel.substring(0, rel.length()-1);
    }
	
	
	/**
	 *  排序加入活动列数据  dangwei 
	 */
	public static String[] SortPicDetailCol(String str,String strDetail) {
		String[] arr = new String[2];
		
		List<String> listPic = new ArrayList<String>();
		List<String> listFile = new ArrayList<String>();
		
		List<String> listPicDetail = new ArrayList<String>();
		List<String> listFileDetail = new ArrayList<String>();

		
		String[] stp = str.split(",");
		String[] stpd = strDetail.split(",");
		
		for (int i = 0; i < stp.length; i++) {
			int index = stp[i].indexOf("图片");
			if(index==0){
				listPic.add(stp[i]);
				listPicDetail.add(stpd[i]);
			}else{
				listFile.add(stp[i]);
				listFileDetail.add(stpd[i]);
			}
		}
		if(listPic!=null && listPic.size()>0){
			arr[0]=list2String(listFile, ",")+","+list2String(listPic, ",");
			arr[1]=list2String(listFileDetail, ",")+","+list2String(listPicDetail, ",");
			return arr;
		}
		arr[0] = list2String(listFile, ",");
		arr[1] = list2String(listFileDetail, ",");
		return arr;
	}
}
